//
//  SelectAddressViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/19.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "SelectAddressViewController.h"
#import "QLMResultAddrTabCell.h"

@interface SelectAddressViewController ()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    
    BMKPinAnnotationView *newAnnotation;
    BMKGeoCodeSearch *_geoCodeSearch;
    BMKReverseGeoCodeOption *_reverseGeoCodeOption;
    BMKLocationService *_locService;
    BMKPoiSearch *_searcher;
    
    UITableViewCell *addrecell;
    NSString *districtString;
    MapAddressModel *resultmodel;
}

@property (nonatomic, strong) NSString *provinceCityDisStr;
@property (strong, nonatomic) UIButton *mapPin;
@property (strong, nonatomic) UITableView *cityTableview;

@property (strong, nonatomic) UITextField *textField;
@property (strong, nonatomic) UIButton *locationServButton;

@property (nonatomic, strong) NSMutableArray *cityDataArr;
@property (nonatomic, strong) BMKMapView *mapView;

@end

@implementation SelectAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"地图选点";
    self.view.backgroundColor=[UIColor whiteColor];
    
    _cityDataArr=[NSMutableArray array];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(kScreen_width-44, 0, 44, 44);
    [rightButton setTitle:@"确定" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor]  forState:UIControlStateNormal];
    rightButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    [rightButton addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                   target:nil
                                   action:nil];
    fixedSpace.width = 0;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:fixedSpace,rightItem,nil];
    
    //初始化检索对象
    _searcher =[[BMKPoiSearch alloc] init];
    _searcher.delegate = self;
    
    UIView *topView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 44)];
    topView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:topView];
    
    UIImageView *searchImaView=[[UIImageView alloc] initWithFrame:CGRectMake(6, 15, 14, 14)];
    searchImaView.image=[UIImage imageNamed:@"search"];
    [topView addSubview:searchImaView];
    
    _textField=[[UITextField alloc] initWithFrame:CGRectMake(25, 0, kScreen_width-25-44, 44)];
    _textField.backgroundColor=[UIColor clearColor];
    _textField.placeholder=@"请输入关键字搜索";
    _textField.font=[UIFont systemFontOfSize:16.0f];
    _textField.delegate=self;
    _textField.textColor=[UIColor darkGrayColor];
    _textField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    _textField.returnKeyType=UIReturnKeySearch;
    [topView addSubview:_textField];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(kScreen_width-44, 0, 44, 44);
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor whiteColor]  forState:UIControlStateNormal];
    searchButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
    searchButton.backgroundColor=kButtonColor;
    [searchButton addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:searchButton];
    
    CGFloat mapViewOriginY=topView.frame.size.height+topView.frame.origin.y;
    _mapView=[[BMKMapView alloc] initWithFrame:CGRectMake(0, mapViewOriginY, kScreen_width, kScreen_height/2-mapViewOriginY/2)];
    _mapView.mapType=BMKMapTypeStandard;
    [self.view addSubview:_mapView];
    
    _cityTableview=[[UITableView alloc] initWithFrame:CGRectMake(0, kScreen_height/2+mapViewOriginY/2, kScreen_width, kScreen_height/2-mapViewOriginY/2-QLM_StatusBarAndNavigationBarHeight)];
    _cityTableview.dataSource=self;
    _cityTableview.delegate=self;
    _cityTableview.showsVerticalScrollIndicator=NO;
    _cityTableview.backgroundColor=[UIColor clearColor];
    _cityTableview.tableFooterView=[[UIView alloc] initWithFrame:CGRectZero];
    _cityTableview.tableHeaderView=[[UIView alloc] initWithFrame:CGRectZero];
    _cityTableview.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_cityTableview];
    
    _mapPin=[UIButton buttonWithType:UIButtonTypeCustom];
    _mapPin.frame=CGRectMake(kScreen_width/2-35/2, (kScreen_height/2-mapViewOriginY/2-35)/2,35, 35);
    [_mapPin setBackgroundColor:[UIColor clearColor]];
    [_mapPin setImage:[UIImage imageNamed:@"dingweipin"] forState:UIControlStateNormal];
    _mapPin.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_mapView addSubview:_mapPin];
    
    _locationServButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _locationServButton.frame=CGRectMake(kScreen_width-50, kScreen_height/2-mapViewOriginY/2-35-10, 50, 50);
    [_locationServButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_locationServButton setBackgroundColor:[UIColor clearColor]];
    [_locationServButton setImage:[UIImage imageNamed:@"map_loaction"] forState:UIControlStateNormal];
    [_locationServButton addTarget:self action:@selector(startLocationService:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:_locationServButton];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [_mapView viewWillAppear];
    _mapView.delegate=self;
    [self initLocationService];
    
    if (_isEditable) {
        _textField.text=_addressDetailStr;
        [self startSearchAddress:_addressDetailStr];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [_mapView viewWillDisappear];
    _mapView.delegate=nil;
    [_textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Action
- (void)leftClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightClick{
    if (self.cityDataArr.count!=0) {
        if (resultmodel.address.length==0) {
            resultmodel=self.cityDataArr[0];
        }
    }
    [self reuqestAddressInfoDataWithLatitude];
}

#pragma mark - 请求数据
- (void)reuqestAddressInfoDataWithLatitude{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    NSString *userid=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId];
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:userid forKey:@"userId"];
    if (_provinceCityDisStr.length==0) {
        ETToast(@"请选择地址");
        return;
    }
    [paramerDic setObject:_provinceCityDisStr forKey:@"addressKey"];
    
    [paramerDic setObject:[NSString stringWithFormat:@"%@",resultmodel.name] forKey:@"addressVal"];
    [paramerDic setObject:@(resultmodel.latitude) forKey:@"addressLatitude"];
    [paramerDic setObject:@(resultmodel.longitude) forKey:@"addressLongitude"];
    
    if (_isEditable){
        [paramerDic setObject:_addressIdStr forKey:@"userAddressId"];
    }
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/saveAddress" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToast(responseObject[@"msg"]);
                            [self.navigationController popViewControllerAnimated:YES];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)returnText:(MapBlock)block{
    self.block=block;
}

- (void)startLocationService:(UIButton *)sender{
    [_locService startUserLocationService];
}

- (void)startSearchAddress:(NSString *)keywordString{
    
    [_locService stopUserLocationService];
    //构造行政区域检索信息类
    BMKCitySearchOption *option = [[BMKCitySearchOption alloc] init];
    option.pageIndex = 0;
    option.pageCapacity = 20;
    option.city=districtString;
    option.keyword = keywordString;
    //发起检索
    BOOL flag = [_searcher poiSearchInCity:option];
    if (flag) {
        NSLog(@"检索发送成功");
    } else {
        NSLog(@"检索发送失败");
    }
}

- (void)searchClick{
    [_textField resignFirstResponder];
    if (_textField.text.length!=0) {
        [self startSearchAddress:_textField.text];
    }
}

#pragma mark - UITextField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self searchClick];
    return YES;
}

#pragma mark  tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cityDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    QLMResultAddrTabCell *addrecell=[QLMResultAddrTabCell cellWithTableView:tableView];
    addrecell.selectionStyle=UITableViewCellSelectionStyleNone;
    addrecell.tintColor=[UIColor greenColor];
    
    MapAddressModel *rmodel=self.cityDataArr[indexPath.row];
    addrecell.nameLabel.text=rmodel.name;
    addrecell.detailLabel.text=rmodel.address;
    return addrecell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array =[tableView visibleCells];
    for (UITableViewCell *cell in array) {
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
     resultmodel=self.cityDataArr[indexPath.row];
    _textField.text=resultmodel.name;
}

#pragma mark 设置cell分割线做对齐
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

-(void)viewDidLayoutSubviews {
    
    if ([self.cityTableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.cityTableview setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.cityTableview respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.cityTableview setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark - 搜索结果回调
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error{
    [self.cityDataArr removeAllObjects];
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        for(BMKPoiInfo *poiInfo in poiResultList.poiInfoList){
            MapAddressModel *model=[[MapAddressModel alloc]init];
            model.name=poiInfo.name;
            model.address=poiInfo.address;
            model.latitude=poiInfo.pt.latitude;
            model.longitude=poiInfo.pt.longitude;
            [self.cityDataArr addObject:model];
        }
        
        BMKPoiInfo *firstpoiInfo = poiResultList.poiInfoList[0];
        _mapView.centerCoordinate = firstpoiInfo.pt;

        if (self.cityDataArr.count!=0) {
            [self tableView:_cityTableview didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        }
        
    }else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        ETToast(@"起始点有歧义");
    } else {
        ETToast(@"抱歉，未找到结果");
    }
    
    [self.cityTableview reloadData];
}

#pragma mark 初始化地图，定位
-(void)initLocationService{
    
    [_mapView setMapType:BMKMapTypeStandard];// 地图类型 ->卫星／标准、
    
    [_mapView setChangeWithTouchPointCenterEnabled:YES];
    _mapView.zoomLevel=17;
    _mapView.showsUserLocation = YES;
    
    [_mapView bringSubviewToFront:_mapPin];
    
    if (_locService==nil) {
        _locService = [[BMKLocationService alloc]init];
        [_locService setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    
    _locService.delegate = self;
    
    if (!_isEditable) {
        [_locService startUserLocationService];
    }
    
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
}

#pragma mark BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    _mapView.showsUserLocation = YES;//显示定位图层
    //设置地图中心为用户经纬度
    [_mapView updateLocationData:userLocation];
    _mapView.centerCoordinate = userLocation.location.coordinate;

    BMKCoordinateRegion region ;//表示范围的结构体
    region.center = _mapView.centerCoordinate;//中心点
    region.span.latitudeDelta = 0.004;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
    region.span.longitudeDelta = 0.004;//纬度范围
    [_mapView setRegion:region animated:YES];
}

#pragma mark BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    [_locService stopUserLocationService];
    //屏幕坐标转地图经纬度
    CLLocationCoordinate2D MapCoordinate=[_mapView convertPoint:_mapPin.center toCoordinateFromView:_mapView];
    if (_geoCodeSearch==nil) {
        //初始化地理编码类
        _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
        _geoCodeSearch.delegate = self;
    }
    if (_reverseGeoCodeOption==nil) {
        //初始化反地理编码类
        _reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    }
    
    //需要逆地理编码的坐标位置
    _reverseGeoCodeOption.reverseGeoPoint = MapCoordinate;
    [_geoCodeSearch reverseGeoCode:_reverseGeoCodeOption];
}

#pragma mark BMKGeoCodeSearchDelegate
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    
    [self.cityDataArr removeAllObjects];
    //获取周边用户信息
    if (error==BMK_SEARCH_NO_ERROR) {
        districtString=result.addressDetail.district;
        _provinceCityDisStr=[NSString stringWithFormat:@"%@%@%@",result.addressDetail.province,result.addressDetail.city,result.addressDetail.district];
        
        for(BMKPoiInfo *poiInfo in result.poiList){
            MapAddressModel *model=[[MapAddressModel alloc]init];
            model.name=poiInfo.name;
            model.address=poiInfo.address;
            model.latitude=poiInfo.pt.latitude;
            model.longitude=poiInfo.pt.longitude;
            
            [self.cityDataArr addObject:model];
        }
        
        if (self.cityDataArr.count!=0) {
            [self tableView:_cityTableview didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        }
        
    }else{
        NSLog(@"BMKSearchErrorCode: %u",error);
    }
    
    [self.cityTableview reloadData];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
